package com.sixseven.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sixseven.bean.Member;
import com.sixseven.mapper.MemberMapper;
import com.sixseven.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Belly
 * @version 1.1.0
 */
@Service
@Slf4j
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Override
    public int userRegister(Member member) {
        if (member == null){
            log.info("user register failed, member is Empty");
            return -1;
        }
        if (!StringUtils.hasText(member.getUsername())){
            return -1;
        }
        if (!StringUtils.hasText(member.getPassword())){
            return -1;
        }
        if (!StringUtils.hasText(member.getEmail())){
            return -1;
        }
        //用户名是否存在
        LambdaQueryWrapper<Member> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(Member::getUsername, member.getUsername());
        if (this.getOne(objectLambdaQueryWrapper) != null){
//            log.info("用户名存在");
            return -2;
        }
        //加密
        member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        member.setStatus(0);

        this.save(member);
        return 1;
    }

    @Override
    public Member userLogin(Member member, HttpServletRequest request) {
        if (member == null){
            log.info("user login failed, member is Empty");
            return null;
        }

        //查询用户是否存在
        LambdaQueryWrapper<Member> objectLambdaQueryWrapper = Wrappers.lambdaQuery();
        objectLambdaQueryWrapper.eq(Member::getUsername, member.getUsername());
        objectLambdaQueryWrapper.eq(Member::getPassword,
                DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
        Member one = this.getOne(objectLambdaQueryWrapper);
        if (one == null){
            log.info("user login failed, 用户不存在");
            return null;
        }

        //用户脱敏
        one.setPassword("");

        //记录用户登录态
        request.getSession().setAttribute("member", one);
        return one;
    }

    @Override
    public List<Member> memberList(String searchName) {
        LambdaQueryWrapper<Member> memberLambdaQueryWrapper = Wrappers.lambdaQuery();
        memberLambdaQueryWrapper.like(Member::getUsername, searchName);
        List<Member> list = this.list(memberLambdaQueryWrapper);
        //用户脱敏
        for (Member member : list) {
            member.setPassword("******");
        }
        return list;
    }

}
